/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;

namespace Xceed.Silverlight.Data
{
  internal sealed class DataSourceProviderHelper : IDataHelper
  {
    internal DataSourceProviderHelper( 
      DataSourceProvider dataSource, 
      GroupHandler groupHandler,
      SortingHandler sortHandler )
    {
      if( dataSource == null )
        throw new ArgumentNullException( "dataSource" );

      m_dataSource = dataSource;
      m_groupHandler = groupHandler;
      m_sortHandler = sortHandler;
    }

    public IEnumerable<String> GroupedPropertyNames
    {
      get
      {
        return m_groupHandler.PropertyNames;
      }
    }

    internal static bool TryGetSortPositionValue(
      string memberName,
      SortPosition sortPosition,
      out object value )
    {
      value = null;

      IList<SortDescription> sortFields = sortPosition.SortingReference;
      IList<object> sortValues = sortPosition.SortValues;
      bool found = false;

      for( int i = 0; i < sortFields.Count; i++ )
      {
        if( !object.Equals( sortFields[ i ].PropertyName, memberName ) )
          continue;

        found = ( i < sortValues.Count );

        if( found )
        {
          value = sortValues[ i ];
        }

        break;
      }

      return found;
    }

    #region IDataHelper Members

    public SortDescription[] CompleteSort
    {
      get
      {
        List<SortDescription> sortDescriptions = new List<SortDescription>();

        List<string> groupProperties =
          ( m_groupHandler != null )
          ? m_groupHandler.PropertyNames.ToList()
          : null;

        ILookup<string, SortDescription> sortLookup =
          ( m_sortHandler != null )
          ? m_sortHandler.SortDescriptions.ToLookup( ( sort ) => sort.PropertyName )
          : null;

        if( groupProperties != null )
        {
          foreach( string groupProperty in groupProperties )
          {
            if( m_sortHandler != null && sortLookup.Contains( groupProperty ) )
            {
              sortDescriptions.Add( sortLookup[ groupProperty ].First() );
            }
            else
            {
              sortDescriptions.Add( new SortDescription( groupProperty, ListSortDirection.Ascending ) );
            }
          }
        }

        if( m_sortHandler != null )
        {
          foreach( SortDescription sortDescription in m_sortHandler.SortDescriptions )
          {
            if(groupProperties == null || !groupProperties.Contains( sortDescription.PropertyName ) )
            {
              sortDescriptions.Add( sortDescription );
            }
          }
        }

        foreach( SortDescription description in m_dataSource.PrimaryKeyInfo )
        {
          if( !sortDescriptions.Any(
            ( sortDescription ) => object.Equals( sortDescription.PropertyName, description.PropertyName ) ) )
          {
            sortDescriptions.Add( description );
          }
        }

        return sortDescriptions.ToArray();
      }
    }

    public object Convert( object value )
    {
      return m_dataSource.WrapDataObject( value );
    }

    public object ConvertBack( object value )
    {
      object obj = value;
      RawDataItem dataItem = value as RawDataItem;

      if( dataItem != null )
      {
        obj = m_dataSource.UnwrapDataObject( dataItem );
      }

      return obj;
    }

    public object GetMemberValue( string memberName, object item )
    {
      object value;

      if( !this.TryGetMemberValue( memberName, item, out value ) )
        throw new ArgumentException( "The specified member was not found on the item.", "memberName" );

      return value;
    }

    public bool TryGetMemberValue( string memberName, object item, out object value )
    {
      value = null;

      RawDataItem dataItem = item as RawDataItem;

      if( dataItem != null )
        return dataItem.TryGetDataMemberValue( memberName, out value );

      SortPosition sortPosition = item as SortPosition;

      if( sortPosition != null )
        return DataSourceProviderHelper.TryGetSortPositionValue(
                 memberName,
                 sortPosition,
                 out value );

      return false;
    }

    public int Compare( object firstItem, object secondItem )
    {
      SortPosition firstSortPosition = firstItem as SortPosition;
      SortPosition secondSortPosition = secondItem as SortPosition;
      IList<SortDescription> sortDescriptions = null;
      int comparisonCount = 0;

      //If one of the items is a SortPosition, we compare items
      //based on the SortPosition's sorting reference.
      if( firstSortPosition == null && secondSortPosition == null )
      {
        sortDescriptions = this.CompleteSort.ToList();
        comparisonCount = sortDescriptions.Count;
      }
      if( firstSortPosition != null && secondSortPosition == null )
      {
        sortDescriptions = firstSortPosition.SortingReference;
        comparisonCount = firstSortPosition.SortValues.Count;
      }
      else if( firstSortPosition == null && secondSortPosition != null )
      {
        sortDescriptions = secondSortPosition.SortingReference;
        comparisonCount = secondSortPosition.SortValues.Count;
      }
      else if( firstSortPosition != null && secondSortPosition != null )
      {
        //Both items are SortPosition.
        comparisonCount = Math.Min( firstSortPosition.SortValues.Count, secondSortPosition.SortValues.Count );

        //Both SortingReferences must be the same in order to compare them.
        for( int i = 0; i < comparisonCount; i++ )
        {
          if( !object.Equals( firstSortPosition.SortingReference[ i ], secondSortPosition.SortingReference[ i ] ) )
            throw new InvalidOperationException( "An attempt was made to compare two objects that cannot be compared." );
        }

        //Using the first SortPosition's sorting or the second SortPosition's sorting
        //is not important since they are the same in the scope of the comparison.
        sortDescriptions = firstSortPosition.SortingReference;
      }

      int compareResult = 0;

      for( int i = 0; ( i < comparisonCount ) && ( compareResult == 0 ); i++ )
      {
        object firstValue;
        object secondValue;
        string memberName = sortDescriptions[ i ].PropertyName;
        bool firstValueResult = this.TryGetMemberValue( memberName, firstItem, out firstValue );
        bool secondValueResult = this.TryGetMemberValue( memberName, secondItem, out secondValue );

        if( !firstValueResult || !secondValueResult )
          throw new InvalidOperationException( "An attempt was made two compare a child with a parent object." );

        compareResult = this.CompareValues( firstValue, secondValue, sortDescriptions[ i ] );
      }

      //If we compare one or two SortPositions, 
      //equality is subject to SortPosition's StartPosition property
      if( compareResult == 0 )
      {
        if( firstSortPosition != null && secondSortPosition != null )
        {
          if( firstSortPosition.SortValues.Count < secondSortPosition.SortValues.Count )
          {
            //Second SortPosition is "inside" the first SortPosition. 
            compareResult = ( firstSortPosition.StartPosition == StartPosition.Before ) ? -1 : 1;
          }
          else if( secondSortPosition.SortValues.Count < firstSortPosition.SortValues.Count )
          {
            compareResult = ( secondSortPosition.StartPosition == StartPosition.Before ) ? 1 : -1;
          }
          else if( firstSortPosition.StartPosition != secondSortPosition.StartPosition )
          {
            Debug.Assert( firstSortPosition.SortValues.Count == secondSortPosition.SortValues.Count );
            compareResult = ( firstSortPosition.StartPosition == StartPosition.Before ) ? -1 : 1;
          }
        }
        else if( firstSortPosition != null && secondSortPosition == null )
        {
          compareResult = ( firstSortPosition.StartPosition == StartPosition.Before ) ? -1 : 1;
        }
        else if( firstSortPosition == null && secondSortPosition != null )
        {
          compareResult = ( secondSortPosition.StartPosition == StartPosition.Before ) ? 1 : -1;
        }
      }

      return compareResult;
    }

    public int CompareValues( object firstValue, object secondValue, string propertyName )
    {
      int compareResult;

      if( firstValue == secondValue )
      {
        compareResult = 0;
      }
      else if( firstValue == null )
      {
        compareResult = -1;
      }
      else if( secondValue == null )
      {
        compareResult = 1;
      }
      else
      {
        compareResult = ( ( IComparable )firstValue ).CompareTo( secondValue );
      }

      return compareResult;
    }

    public void InvalidateItem( object item )
    {
      if( m_dataSource == null || item == null )
        return;

      RawDataItem dataItem = item as RawDataItem;
      if( dataItem != null )
      {
        m_dataSource.InvalidateDataItem( dataItem );
      }
    }

    #endregion IDataHelper Members


    #region Private Fields

    private DataSourceProvider m_dataSource; //null
    private GroupHandler m_groupHandler;//null
    private SortingHandler m_sortHandler;//null

    #endregion Private Fields
  }
}
